//
//  RSChooseTimePickerViewTwo.m
//  RSChooseTimeCase
//
//  Created by thinkjoy on 16/9/9.
//  Copyright © 2016年 Thinkjoy_RS. All rights reserved.
//

#import "RSChooseTimePickerViewTwo.h"

#define kWinH [[UIScreen mainScreen] bounds].size.height
#define kWinW [[UIScreen mainScreen] bounds].size.width

////宽高比系数
#define WFACTOR (kWinW/320)
#define HFACTOR (kWinH/480)

#pragma mark - 日志开关
#ifdef DEBUG
#define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#define DLog(...)
#endif

@interface RSChooseTimePickerViewTwo ()<UIPickerViewDelegate,UIPickerViewDataSource>
@property(nonatomic,strong) UIView      * pickerViewCase;
@property(nonatomic,strong) UIButton    *bgButton;
@property   (nonatomic,strong)  UIPickerView    *   pickerView;

//存放  年  月 日 时 分 的数组
@property   (nonatomic,strong)  NSMutableArray * yearMuAry;
@property   (nonatomic,strong)  NSArray * monthAry;
@property   (nonatomic,strong)  NSArray * hourAry;
@property   (nonatomic,strong)  NSMutableArray * minuAry;
@property   (nonatomic,strong)  NSMutableArray * dayMuAry;


//当前的时间
@property   (nonatomic,assign)  NSInteger    nowYear;
@property   (nonatomic,assign)  NSInteger    nowMonth;
@property   (nonatomic,assign)  NSInteger    nowDay;
@property   (nonatomic,assign)  NSInteger    nowHour;
@property   (nonatomic,assign)  NSInteger    nowMinu;


@property   (nonatomic,assign)  NSInteger   yearRow;
@property   (nonatomic,assign)  NSInteger   monthRow;
@property   (nonatomic,assign)  NSInteger   dayRow;
@property   (nonatomic,assign)  NSInteger   hourRow;
@property   (nonatomic,assign)  NSUInteger  minuRow;

@property   (nonatomic,copy)    NSString    * chooseTimeStr;

@end

@implementation RSChooseTimePickerViewTwo

- (instancetype)init
{
    self    =   [super init];
    if (self) {
        self.frame  =   CGRectMake(0, 0, kWinW, kWinH);
        [[[UIApplication sharedApplication] keyWindow] addSubview:self];
        //半透明背景按钮
        _bgButton = [[UIButton alloc]init];
        [self addSubview:_bgButton];
        [_bgButton addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
        _bgButton.tag   =   100;
        _bgButton.backgroundColor = [UIColor blackColor];
        _bgButton.alpha = 0;
        _bgButton.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        
        _pickerViewCase =   [[UIView alloc]initWithFrame:CGRectMake( 0, kWinH, kWinW, kWinH/3)];
        [self    addSubview:_pickerViewCase];
        _pickerViewCase.backgroundColor =   [UIColor whiteColor];
        
        UIView  * titleView =   [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWinW, 44)];
        titleView.backgroundColor  =   [UIColor whiteColor];
        [_pickerViewCase addSubview:titleView];
        
        UILabel * titleLabel    =   [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.pickerViewCase.frame.size.width, self.pickerViewCase.frame.size.height*7.0/43.0)];

        titleLabel.text =   @"请选择时间";
        titleLabel.textAlignment    =   NSTextAlignmentCenter;
        titleLabel.textColor    =   [UIColor lightGrayColor];
        [self.pickerViewCase    addSubview:titleLabel];
        
        UIButton    * commitButt    =   [UIButton buttonWithType:UIButtonTypeCustom];
        [titleView   addSubview:commitButt];
        commitButt.frame    =   CGRectMake(CGRectGetWidth(titleView.frame)-70, 0, 60, CGRectGetHeight(titleView.frame));
        //        [commitButt mas_makeConstraints:^(MASConstraintMaker *make) {
        //            make.width.mas_equalTo(60);
        //            make.right.mas_equalTo(titleView.mas_right).mas_offset(-10);
        //            make.height.mas_equalTo(titleView.mas_height);
        //            make.centerY.mas_equalTo(titleView.mas_centerY);
        //        }];
        //        [commitButt  setBackgroundColor:[UIColor colorWithHexString:NAV_TitleBgColor]];
        [commitButt  setTitle:@"确定" forState:UIControlStateNormal];
        [commitButt setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
        commitButt.tag  =   200;
        [commitButt  addTarget:self action:@selector(dismissDatePicker:) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton    * dismissButt    =   [UIButton buttonWithType:UIButtonTypeCustom];
        [titleView   addSubview:dismissButt];
        dismissButt.frame    =   CGRectMake(10, 0, 60, CGRectGetHeight(titleView.frame));

        //        [commitButt  setBackgroundColor:[UIColor colorWithHexString:NAV_TitleBgColor]];
        [dismissButt  setTitle:@"取消" forState:UIControlStateNormal];
        [dismissButt setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        dismissButt.tag  =   300;
        [dismissButt  addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
        
        
        _pickerView    =   [[UIPickerView alloc]init];
        [_pickerViewCase addSubview:_pickerView];
        
        _pickerView.frame   =   CGRectMake(0, CGRectGetMaxY(titleView.frame), CGRectGetWidth(_pickerViewCase.frame), CGRectGetHeight(_pickerViewCase.frame)-CGRectGetHeight(titleView.frame));
        //        [_pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        //            make.left.mas_equalTo(_pickerViewCase.mas_left);
        //            make.right.mas_equalTo(_pickerViewCase.mas_right);
        //            make.top.mas_equalTo(titleView.mas_bottom);
        //            make.bottom.mas_equalTo(_pickerViewCase.mas_bottom);
        //        }];
        
        self.pickerView.delegate    =   self;
        self.pickerView.dataSource  =   self;
        
//        [self    getNowTime];   //获得设备当时的时间
        [self    sourceAry];    //获得数据源

        [self.pickerView  selectRow:self.nowDay inComponent:0 animated:YES];
        [self.pickerView  selectRow:self.nowHour inComponent:1 animated:YES];
        
        if (self.nowMinu<50) {
            [self.pickerView  selectRow:self.nowMinu/10+1 inComponent:2 animated:YES];
        }else{
            [self.pickerView  selectRow:0 inComponent:2 animated:YES];
            [self mimuFullIntoHour];
        }
        
        [self.pickerViewCase    addSubview:self.pickerView];
        
        self.dayRow     =   [self.pickerView selectedRowInComponent:0];
        self.hourRow    =   [self.pickerView selectedRowInComponent:1];
        self.minuRow    =   [self.pickerView selectedRowInComponent:2];
        
    }
    
    [self performSelector:@selector(show) withObject:self afterDelay:0.1];
    return self;
}
/**
 *  分满进位
 */
- (void)mimuFullIntoHour
{
    if (self.nowHour+1>=self.hourAry.count) {
        [self.pickerView selectRow:0 inComponent:1 animated:YES];
        [self HourFullIntoDay];
    }else{
        [self.pickerView selectRow:self.nowHour+1 inComponent:1 animated:YES];
    }

}
/**
 *  时满了就进位
 */
- (void)HourFullIntoDay
{
    [self.pickerView selectRow:[self.pickerView selectedRowInComponent:0]+1 inComponent:0 animated:YES];

}
- (void)show
{
    
    //发送通知,弹框出现,退出键盘
    //    [[NSNotificationCenter defaultCenter]postNotificationName:EndEdit object:self];
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    [UIView animateWithDuration:0.3 animations:^{
        _pickerViewCase.frame =    CGRectMake( 0, kWinH-kWinH/3, kWinW, kWinH/3);
        _bgButton.alpha =   0.3;
    } completion:^(BOOL finished) {
        
    }];
}
- (void)dismiss
{
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        _pickerViewCase.frame =   CGRectMake( 0, kWinH, kWinW, kWinH/3);
        _bgButton.alpha =   0;
    } completion:^(BOOL finished) {
        [_pickerViewCase removeFromSuperview];
        [_bgButton removeFromSuperview];
        [weakSelf removeFromSuperview];
    }];
}
#pragma mark    UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return self.dayMuAry.count;
            break;
        case 1:
            return self.hourAry.count;
            break;
        case 2:
            return self.minuAry.count;
            break;
        default:
            break;
    }
    return 0;
}

#pragma mark UIPickerViewDelegate
//设置列高
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return pickerView.frame.size.height/3.0;//第一组键(列)的高度
}

//返回每列的宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return pickerView.frame.size.width/3.0;
}

//给行赋值
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    switch (component) {
        case 0:
            return self.dayMuAry[row];
            break;
        case 1:
            return [NSString stringWithFormat:@"%@点",self.hourAry[row]];
            break;
        case 2:
            return [NSString stringWithFormat:@"%@分",self.minuAry[row]];
            break;
        default:
            break;
    }
    return 0;
}

#pragma mark    被选中的第几列 的 第几行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    [self getNowTime];
    switch (component) {
        case 0:
        {
            NSInteger   row1    =   [pickerView selectedRowInComponent:1];  //时
            NSInteger   row2    =   [pickerView selectedRowInComponent:2];  //分

            if ([self.dayMuAry[row] isEqualToString:@"今天"]) {
                //如果现在的小时(13)大于pickerView上选择的小时(12),pickerView显示当前小时(13)
                if (self.nowHour>=[self.hourAry[row1] integerValue]) {
                    [self.pickerView  selectRow:self.nowHour inComponent:1 animated:YES];
                    
                    //如果现在的分钟(45)大于pickerView上选择的分钟(40),pickerView显示当前分钟(50)
                    if (self.nowMinu>=[self.minuAry[row2] integerValue]) {
                        if (self.nowMinu<50) {
                            [self.pickerView  selectRow:self.nowMinu/10+1 inComponent:2 animated:YES];
                        }else{
                            [self.pickerView  selectRow:0 inComponent:2 animated:YES];
                            [self mimuFullIntoHour];
                        }
                    }
                }
            }
            self.dayRow     =   [pickerView selectedRowInComponent:0];
            self.hourRow    =   [pickerView selectedRowInComponent:1];
            self.minuRow    =   [pickerView selectedRowInComponent:2];
        }
            
            break;
        case 1:
        {
            NSInteger   row0    =   [pickerView selectedRowInComponent:0];  //天
            NSInteger   row2    =   [pickerView selectedRowInComponent:2];  //分
            
            if ([self.dayMuAry[row0] isEqualToString:@"今天"]) {
                //如果现在的小时(13)大于pickerView上选择的小时(12),pickerView显示当前小时(13)
                if (self.nowHour>=[self.hourAry[row] integerValue]) {
                    [self.pickerView  selectRow:self.nowHour inComponent:1 animated:YES];
                    
                    //如果现在的分钟(45)大于pickerView上选择的分钟(40),pickerView显示当前分钟(50)
                    if (self.nowMinu>=[self.minuAry[row2] integerValue]) {
                        if (self.nowMinu<50) {
                            [self.pickerView  selectRow:self.nowMinu/10+1 inComponent:2 animated:YES];
                        }else{
                            [self.pickerView  selectRow:0 inComponent:2 animated:YES];
                            [self mimuFullIntoHour];
                        }
                    }
                }

            }
            self.dayRow     =   [pickerView selectedRowInComponent:0];
            self.hourRow    =   [pickerView selectedRowInComponent:1];
            self.minuRow    =   [pickerView selectedRowInComponent:2];
        }
            break;
        case 2:
        {
            NSInteger   row0    =   [pickerView selectedRowInComponent:0];  //天
            NSInteger   row1    =   [pickerView selectedRowInComponent:1];  //时
            
            if ([self.dayMuAry[row0] isEqualToString:@"今天"]) {
                //如果现在的小时(13)大于pickerView上选择的小时(12),pickerView显示当前小时(13)
                if (self.nowHour>=[self.hourAry[row1] integerValue]) {
                    [self.pickerView  selectRow:self.nowHour inComponent:1 animated:YES];
                    
                    //如果现在的分钟(45)大于pickerView上选择的分钟(40),pickerView显示当前分钟(50)
                    if (self.nowMinu>=[self.minuAry[row] integerValue]) {
                        if (self.nowMinu<50) {
                            [self.pickerView  selectRow:self.nowMinu/10+1 inComponent:2 animated:YES];
                        }else{
                            [self.pickerView  selectRow:0 inComponent:2 animated:YES];
                            [self mimuFullIntoHour];
                        }
                    }
                }
                
            }
            self.dayRow     =   [pickerView selectedRowInComponent:0];
            self.hourRow    =   [pickerView selectedRowInComponent:1];
            self.minuRow    =   [pickerView selectedRowInComponent:2];
        }
            
            break;
        default:
            break;
    }
    
}

//数据源
- (void)sourceAry
{
    [self    getNowTime];   //获得设备当时的时间
    self.dayMuAry   =   [[NSMutableArray alloc]initWithArray:@[@"今天",@"明天"]];
    self.hourAry    =   [NSArray arrayWithObjects:@"00",@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23", nil];
    self.minuAry    =   [[NSMutableArray alloc]initWithArray:@[@"00",@"10",@"20",@"30",@"40",@"50"]];
}

#pragma mark    获得当前的时间,年,月,日,时,分
- (void)getNowTime
{
    NSDate *nowDate =   [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"yyyy-MM-dd-HH-mm"];
    
    NSString    * nowDateStr    =   [formatter stringFromDate:nowDate];
    
    DLog(@"%@",nowDateStr);
    
    NSArray * array   =   [nowDateStr componentsSeparatedByString:@"-"];
    
    self.nowYear    =   [array[0] integerValue];
    self.nowMonth   =   [array[1] integerValue];
    self.nowDay     =   [array[2] integerValue];
    self.nowHour    =   [array[3] integerValue];
    DLog(@"%ld",(long)self.nowHour);
    self.nowMinu    =   [array[4] integerValue];
    //    self.nowYear    =   2016;
    //    self.nowMonth   =   12;
    //    self.nowDay     =   31;
//        self.nowHour    =   13;
//        self.nowMinu    =   45;
    //
}

#pragma mark计算当前年,当前月的天数
- (NSInteger)getDaysWithYearAndMonth
{
    NSInteger month =   [self.pickerView selectedRowInComponent:1]+1; //选择器的月数
    NSInteger year   =   [self.pickerView selectedRowInComponent:0]+2016; //选择器年的行数
    
    if (month==1||month==3||month==5||month==7||month==8||month==10||month==12) {
        return 31;
    }else if(month==4||month==6||month==9||month==11){
        return 30;
    }else if (((year%4==0)&&(year%100!=0))||(year%400==0)){
        return 29;
    }else{
        return 28;
    }
}

#pragma mark把日期拼接到一起
- (NSString *)getSelectTimeStr
{
    NSString    *dayStr     =   self.dayMuAry[self.dayRow];
    if ([dayStr isEqualToString:@"今天"]) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        dayStr  =   [formatter stringFromDate:[NSDate date]];
    }else if ([dayStr isEqualToString:@"明天"]){
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        dayStr  =   [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:24*60*60]];
    }
    NSString    *hourStr    =   self.hourAry[self.hourRow];
    NSString    *minuStr    =   self.minuAry[self.minuRow];

    
    NSString    * str = [NSString stringWithFormat:@"%@ %@:%@",dayStr,hourStr,minuStr];
    DLog(@"%@",str);
    return str;
}

//消失
- (void)dismissDatePicker:(UIButton *)butt
{
//    NSString    *yearStr    =   self.yearMuAry[self.yearRow];
//    NSString    *monthStr   =   self.monthAry[self.monthRow];
//    
//    NSString    *dayStr     =   nil;
//    if (self.dayRow+1<10) {
//        dayStr     =   [NSString stringWithFormat:@"0%ld",(long)self.dayRow+1];
//    }else{
//        dayStr     =   [NSString stringWithFormat:@"%ld",(long)self.dayRow+1];
//    }
//    
//    NSString    *minStr     =   [NSString stringWithFormat:@"%@:%@",self.hourAry[self.hourRow],self.minuAry[self.minuRow]];
//    
//    NSString    * str = [NSString stringWithFormat:@"%@-%@-%@ %@",yearStr,monthStr,dayStr,minStr];
    
    
    if ([self respondsToSelector:@selector(chooseTimePickerViewTwo:getUseTime:)]) {
        [self.delegate  chooseTimePickerViewTwo:self getUseTime:[self getSelectTimeStr]];
    }
    
    
//    NSString    * timeStr   =   (self.chooseTimeStr!=nil)?_chooseTimeStr:str;
    if (self.chooseTimeViewBlock) {
        self.chooseTimeViewBlock([self getSelectTimeStr]);
    }
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.pickerViewCase.frame = CGRectMake(30*WFACTOR, kWinH, 260*WFACTOR, 160*WFACTOR);
        weakSelf.bgButton.alpha = 0.0;
        
    } completion:^(BOOL finished) {
        [weakSelf.pickerViewCase removeFromSuperview];
        [weakSelf.bgButton removeFromSuperview];
        [weakSelf removeFromSuperview];
        
    }];
}

#pragma mark    自定义pickerLabel的样式
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *pickerLabel = (UILabel *)view;
    if (!pickerLabel)
    {
        pickerLabel = [[UILabel alloc] init];
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setFont:[UIFont systemFontOfSize:16]];
    }
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    
    return pickerLabel;
}


@end
